package com.uni.controllers;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.uni.controllers.binding.Messager;
import com.uni.controllers.editors.GroupEditor;
import com.uni.controllers.validation.UserValidator;
import com.uni.db.FileService;
import com.uni.db.GenericService;
import com.uni.domain.File;
import com.uni.domain.Group;
import com.uni.domain.Status;
import com.uni.domain.User;
import com.uni.utils.FileUtils;

@Controller
@RequestMapping("/editUser.htm")
@SessionAttributes(types = User.class)
public class UserEdit {
	
	@Autowired
    @Qualifier("userService")
    private GenericService<User> userService;
	
	@Autowired
    @Qualifier("groupService")
    private GenericService<Group> groupService;
	
	@Autowired
    @Qualifier("fileService")
    private FileService fileService;

	
	@RequestMapping(method = RequestMethod.GET)
    public String setupForm(@RequestParam(value = "id", required = false) Long id, ModelMap model) throws UnsupportedEncodingException {
        User user;
        if (id == null || id < 1) {
            user = new User();
        } else {
            user = userService.get(id);
        }
        if(user == null){
        	model.addAttribute("title", "user edit error");
            model.addAttribute("message", "id not specified");
            return "error";
        }
        model.addAttribute("user", user);
        return "userEdit";
    }
	
	@RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute User user, 
					    		BindingResult result, 
					    		SessionStatus status, 
					    		HttpServletRequest request,
					    		@RequestParam("photoFile") CommonsMultipartFile photo)
	throws IOException, ServletException, FileUploadException {
		System.out.println(request.getAttribute("id"));
		User oldUser = userService.get(user.getId());
        String oldPassword = oldUser != null ? oldUser.getPassword() : null;
        new UserValidator().validate(user, result, request, oldPassword);
        if (result.hasErrors()) {
            return "userEdit";
        }
        if(photo != null && !photo.isEmpty()){
        	if(user.getPhoto() != null){
        		fileService.delete(user.getPhoto());
        	}
        	File photoFile = FileUtils.parseFile(photo, "photo", fileService);
        	user.setPhoto(photoFile);
        }
        userService.save(user);
        status.setComplete();
        return "redirect:/user/" + user.getId();
	}
	
	@InitBinder
    public void initBinder(WebDataBinder binder){
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(Group.class, new GroupEditor(groupService));
        binder.setBindingErrorProcessor(new Messager()); 
    }
 
    @ModelAttribute("groups")
    public Collection<Group> populateGroups(){
        return groupService.listAll();
    }

    @ModelAttribute("statuses")
    public Collection<Status> populateStatuses(){
        return Arrays.asList(Status.values());
    }
}
